package com.nowcoder.community.controller;

import com.nowcoder.community.dao.DiscussPostMapper;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.UserService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {
    @Autowired
    private DiscussPostMapper discussPostMapper;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    //springMVC自动将page对象注入到model中
    //不需要手动设置，
    //斌且可以在tf中直接访问page中的数据
    @RequestMapping(path="/index", method = RequestMethod.GET)
    public String getIndexPage(Model model ,Page page) {
        page.setRows(discussPostService.findDiscussPostCount(0));
        page.setPath("/index");

        List<DiscussPost> list =discussPostService.findDiscussPosts(0,page.getOffset(),page.getLimit());
        System.out.println(page.getLimit());
        List<Map<String, Object>> discussPosts =new ArrayList<>();
        if (list !=null) {
            for (DiscussPost post :list) {
                Map<String, Object> map =new HashMap<>();
                map.put("post",post);
                System.out.println(post.getCreateTime());
                System.out.println(post.getTitle());
                User user = userService.findUserById(post.getUserId());
                map.put("user",user);
                discussPosts.add(map);
            }
        }

        model.addAttribute("discussPosts",discussPosts);
        return "/index";
    }

    @RequestMapping(path = "/logout",method = RequestMethod.GET)
    public String logout(@CookieValue("ticket") String ticket) {
        userService.logout(ticket);
        return "redirect:/index";
    }
}
